package com.hyacinth.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * sql命名工具类
 * <p>校验是否存在sql注入</p>
 * @author zhangfb
 * @version 1.0.0.1
 * @since JDK 1.8
 */
public class NamesSqlUtils {

    //SQL关键字
    private static String SQL_KEY_WORDS = "and|exec|execute|insert|select|delete|update|count|drop|chr|mid|master|truncate|" +
            "char|declare|sitename|net|user|xp_cmdshell|or|like|and|exec|create|drop|alter|call|read|load|lock|convert|revoke|" +
            "set|repeat|table|from|grant|use|group_concat|column_name|" +
            "information_schema|columns|table_schema|union|where|order|by|show|database";

    private static Pattern pattern1 = Pattern.compile("(eval\\((.*)\\)|script)",Pattern.CASE_INSENSITIVE);
    private static Pattern pattern2=Pattern.compile("[\\\"\\'][\\s]*javascript:(.*)[\\\"\\']",Pattern.CASE_INSENSITIVE);
    private static Pattern pattern3 = Pattern.compile("(" + SQL_KEY_WORDS + ")\\s",Pattern.CASE_INSENSITIVE);

    private static Pattern pattern7 = Pattern.compile("(\\/\\*|%|\\*!|\\*\\/|&&|\\|\\||--|!=|<>)",Pattern.CASE_INSENSITIVE);

    public String cleanXSS(String name, Object value) {
        String temp = value.toString();
        Matcher matcher= pattern1.matcher(temp);
        if (matcher.matches()) {
            temp = matcher.replaceAll("");
        }

        matcher=pattern2.matcher(temp);
        if (matcher.matches()) {
            temp = matcher.replaceAll("");
        }
        temp = matcher.replaceAll("\"\"");

        //增加脚本
        temp = temp.replaceAll("script", "")
                .replaceAll("0x0d", "")
                .replaceAll("0x0a", "");
        if(temp.trim().length() > 1 ){
            temp = temp.replaceAll("<", "&lt;").replaceAll(">", "&gt;")
                    .replaceAll("\\(", "（").replaceAll("\\)", "）").replaceAll("=", "equal");
        }
        return temp;
    }

    /**
     * 判断参数是否存在Sql注入
     * 需要增加通配，过滤大小写组合
     * @param key
     * @param value
     * @return
     */
    public boolean isSQLInject(String key, Object value) {
        if ("sign".equals(key)) {
            return false;
        }
        String temp = value.toString();
        if (temp.contains("\\*")) {
            return true;
        }
        if(key.toLowerCase().contains("criteria")){
            if ("like and or".contains(value.toString().toLowerCase())) {
                return false;
            }
        }
        Matcher matcher= pattern3.matcher(temp);
        if (matcher.matches()) {
            return true;
        }
        //替代屏蔽用的符号 */!+-
        Matcher mat = pattern7.matcher( temp );
        return mat.find();

    }
}
